import React, {
  useLayoutEffect,
  useState,
} from "react";
import Header from "../header";
import Main from "../main";
import fetch from "../../util/fetch";
import { useDispatch } from 'react-redux';
import "./index.scss";
import { Loading } from "../../component/common";
import md5 from "md5";
import zhCN from "antd/es/locale/zh_CN";
import {getQueryVariable,removeToken,removeIdentity} from "../../util/public";
import { ConfigProvider } from "antd";
import TaskProcess from "../component/taskProcess"
import {SKIN_BG_COLOR} from '../../hooks/useGetThem'

function App(props) {
  const [init, setInit] = useState(false);
  const [loadVisible, setLoadVisible] = useState(false);
  const dispatch = useDispatch();

  // 获取公共信息
  const getCommonInfo = () => {
    let token = getQueryVariable("lg_tk") || sessionStorage.getItem("token");
    //没有token就掉线
    if(!token){
      return;
    }
    sessionStorage.setItem("token", token);
    dispatch({
      type: "SET_TOKEN",
      data: token
    })
    Promise.all([
      getSysInfo(),
      getUserInfo(),
      // getWorkInfo(),
    ]).then(res => {
      setInit(true)
      linkCheck()
      getSkin()
    }).catch(res => {
      console.log("error", res);
      if(res.code == 401){
        goLogin()
      }
    })
  }
  // 获取用户信息
  const getUserInfo = () => {
    let obj = {
      token: getQueryVariable("lg_tk") || sessionStorage.getItem("token") || ""
    }
    return new Promise((resolve, reject) => {
      fetch.get({
        url: "api/common/user",
        params: obj
      }).then(res => res.json()).then(res => {
        if(!res){
          reject(res)
          return;
        }
        res.data.UserName = decodeURIComponent(res.data.userName);
        sessionStorage.setItem("userInfo", JSON.stringify(res.data));
        sessionStorage.setItem("userId",res.data.userId);
        sessionStorage.setItem("userName",res.data.userName);
        sessionStorage.setItem("userType",res.data.userType);
        sessionStorage.setItem("userClass",res.data.userClass);
        sessionStorage.setItem("schoolType", res.data.schoolLevel)
        sessionStorage.setItem("schoolId", res.data.schoolId)
        dispatch({
          type: "SET_USERINFO",
          data: res.data
        })
        
        // 获取用户身份
        let ic = getQueryVariable("lg_ic") || sessionStorage.getItem("identityCode")
        let isCheck = false
        let identityCode = ""
        let identityInfo = ""
        if(ic){
          Array.isArray(res.data.identityList) && res.data.identityList.forEach(item => {
            if(item.identityCode === ic){
              identityCode = item.identityCode
              identityInfo = item
              isCheck = true
            }
          })
        }
        if(!ic || !isCheck){
          identityCode = res.data.identityList[0].identityCode
          identityInfo = res.data.identityList[0]
        }
        sessionStorage.setItem("identityCode", identityCode);
        sessionStorage.setItem("identityInfo", JSON.stringify(identityInfo));
        dispatch({
          type: "SET_IDENTITYINFO",
          data: identityInfo
        })
        resolve()
      })
    })
  }
  // 获取系统信息
  const getSysInfo = () => {
    return new Promise((resolve, reject) => {
      fetch.get({
        url: "api/common/system/info"
      }).then(res => res.json()).then(res => {
        if(res.code == 200){
          sessionStorage.setItem("baseUrl", res.data.baseUrl)
          sessionStorage.setItem("sysId", res.data.sysId)
          sessionStorage.setItem("sysInfo", JSON.stringify(res.data))
          resolve()
        }else{
          reject(res)
        }
      })
    })
  }
	// 获取消息中心信息
	const getWorkInfo = () => {
		return new Promise((resolve, reject) => {
      let baseUrl = sessionStorage.getItem('baseUrl')
      let mdToken260 = md5('260').split('').reverse().join('')
			fetch
				.get({
					url: baseUrl + "/BaseApi/Global/GetSubSystemsMainServerBySubjectID",
          params: {
            appid: 260,
            access_token: mdToken260,
            sysIDs: '260'
          }
				})
				.then(result => result.json())
				.then(res => {
					if (res.ErrCode == 0 && res.Data) {
            let data = {
                webSvrAddr: res.Data[0].WebSvrAddr,
                wsSvrAddr: res.Data[0].WsSvrAddr
            }
            sessionStorage.setItem('workInfo', JSON.stringify(data));
						resolve();
					} else {
						reject(res);
					}
				});
		});
	};

  const [skin, setSkin] = useState()
  const getSkin = () => {
    return new Promise((resolve, reject) => {
      let baseUrl = sessionStorage.getItem('baseUrl')
			fetch
				.get({
					url: baseUrl + "/openapi/v1/system/facade/getSkin",
          params: {
            appid: 260,
            token: sessionStorage.getItem('token')
          }
				})
				.then(result => result.json())
				.then(res => {
          console.log(res)
          if (res.StatusCode == 200) {
            setSkin(`s${res.Data.skin}`)
            sessionStorage.setItem('skin', `s${res.Data.skin}`)
            resolve()

          }
				});
		});
  }
  // 掉线检测
  const linkCheck = () => {
    let baseUrl = sessionStorage.getItem("baseUrl")
    let token = sessionStorage.getItem("token")
    if(!baseUrl || !token){
      return
    }
    let script = document.createElement("script");
    script.src = baseUrl + "/UserMgr/Login/JS/CheckIsOnline2.js";
    script.type = "text/javascript";
    script.onload = function(){
        window._LgBase_initCheck(baseUrl, token, "E47");
    }
    document.getElementsByTagName("head")[0].appendChild(script);
  }
	// 跳转登录页
	const goLogin = () => {
		let baseUrl = sessionStorage.getItem("baseUrl");
		if (!baseUrl) {
      getSysInfo().catch(() => {goLogin()})
			return;
		}
		let href = removeToken(window.location.href);
		sessionStorage.removeItem("token");
		window.location =
			baseUrl + "/login.html?lg_preurl=" + encodeURIComponent(href);
  };
  const changeLoadVisible = (value) => {
    setLoadVisible(value);
  }
  useLayoutEffect(()=>{
    getCommonInfo();
    window.changeLoadVisible = changeLoadVisible;
  }, []);
  if(!init){
    return <Loading className="app_load" spinning={!init} tip="加载中..."></Loading>
  }
  return (
    <div className="my_app">
      <Loading wrapperClassName="wait_load" spinning={loadVisible} opacity={true} tip=" ">
        <Header />
        <div className="app_body" style={{backgroundColor: SKIN_BG_COLOR[skin]}}>
          <ConfigProvider locale={zhCN}>
          <Main />
          </ConfigProvider>
          {/* <div className="app_footer">蓝鸽科技 版权所有</div> */}
        </div>

        {
          ["IC0001", "IC0002"].includes(sessionStorage.getItem("identityCode"))?
          <TaskProcess
          width={802}
          title="值周应用流程"
          subtitle="值周说明"
          description={
            <>
            <p>教务管理员可以查看值周/值周记录、设置值周类型、设置值日老师、添加/除/编辑值周、查看统计、导出统计/值周记录等操作。</p>
            <p>普通老师可以查看值周/值周记录。</p>
            <p>值周老师可以查看值周/值周记录、编辑值周记录。</p>
            </>
          }/>:
          ""
        }
      </Loading>
    </div>
  )
}

export default App;
